package com.zl.csMall.basic.busFile.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.csMall.basic.busFile.mapper.BusFileMapper;
import com.zl.csMall.basic.busFile.po.BusFile;
import com.zl.csMall.basic.busFile.service.BusFileService;
import com.zl.csMall.code.constant.EntiretyConstant;
import com.zl.csMall.util.Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @description: BusFileServiceImpl
 * @author: ChenNing
 * @date 2025-10-15 15:04
 */
@Service
public class BusFileServiceImpl extends ServiceImpl<BusFileMapper, BusFile> implements BusFileService {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    @Value("${CUSTOM.BUS-FILE.ROOT-PATH}")
    private String ROOT_PATH;
    @Value("${CUSTOM.DOMAIN-NAME}")
    private String DOMAIN_NAME;


    @Override
    public List<String> getDowUrlByAttachmentId(long attachmentId) {
        LambdaQueryWrapper<BusFile> busFileQuery = new LambdaQueryWrapper<>();
        busFileQuery.select(BusFile::getId).eq(BusFile::getAttachmentId, attachmentId).orderByAsc(BusFile::getSort);
        List<Map<String, Object>> idList = this.listMaps(busFileQuery);

        List<String> urlList = new ArrayList<>();
        for (Map<String, Object> map : idList){
            if (map.get("id") != null){
                String filePath = DOMAIN_NAME + EntiretyConstant.BUSFILE_DOWNLOAD_URL + map.get("id").toString();
                urlList.add(filePath);
            }
        }
        return urlList;
    }

    @Override
    public List<String> saveBatchBusFile(long attachmentId, MultipartFile[] fileArr) {
        if (Util.isNullOrEmpty(attachmentId)){
            return null;
        }
        if (fileArr == null || fileArr.length < 1){
            return null;
        }
        List<String> pathList = new ArrayList<>();
        Date date = new Date();

        String savePath = ROOT_PATH + File.separator + sdf.format(date) + File.separator;
        // 检查上传目录是否存在，不存在则创建
        File directory = new File(savePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        List<BusFile> fileList = new ArrayList<>();
        int sort = 0;
        for (MultipartFile multipartFile : fileArr){
            try {
                long busFileId = Util.getUuId();
                BusFile busFile = new BusFile(busFileId, sort, attachmentId, multipartFile.getOriginalFilename(), savePath, date);
                // 物理保存
                File targetFile = new File(directory, String.valueOf(busFileId));
                multipartFile.transferTo(targetFile);
                fileList.add(busFile);

                String filePath = DOMAIN_NAME + EntiretyConstant.BUSFILE_DOWNLOAD_URL + busFileId;
                pathList.add(filePath);
            } catch (IOException e) {
                log.error("ZL-CN【文件保存】异常！multipartFile:" + JSONObject.toJSONString(multipartFile) + " --ERROR:" + e.getMessage(), e);
            }
            sort++;
        }
        boolean result = this.saveBatch(fileList);
        if (result){
            return pathList;
        }
        return null;
    }

    @Override
    public boolean deleteBFile(long id) {
        BusFile busFile = this.getById(id);
        if (busFile == null || busFile.getId() == 0){
            // 文件不存在
            return false;
        }
        boolean result = this.removeById(id);
        if (result){
            Util.deleteFile(busFile.getPath() + busFile.getId());
        }
        return result;
    }

    @Override
    public boolean deleteByAttachmentId(long attachmentId) {
        if (attachmentId == 0){
            return false;
        }
        LambdaQueryWrapper<BusFile> busFileQuery = new LambdaQueryWrapper<>();
        busFileQuery.select(BusFile::getId, BusFile::getPath).eq(BusFile::getAttachmentId, attachmentId);
        List<BusFile> fileList = this.list(busFileQuery);
        boolean result = this.remove(busFileQuery);
        if (result){
            // 删除物理文件
            for (BusFile busFile : fileList){
                Util.deleteFile(busFile.getPath() + busFile.getId());
            }
        }
        return result;
    }

    @Override
    public boolean isExistenceToAttachmentId(Long attachmentId) {
        if (attachmentId == null || attachmentId == 0){
            return false;
        }
        LambdaQueryWrapper<BusFile> busFileQuery = new LambdaQueryWrapper<>();
        busFileQuery.select(BusFile::getId).eq(BusFile::getAttachmentId, attachmentId);
        return this.getBaseMapper().selectCount(busFileQuery) > 0;
    }

}
